﻿using System;
using System.Web.Mvc;
using HXDNB.DAL;

namespace HXDNB.CMS
{
    public class BaseController : Controller
    {
        //登录用户ID  
        public int UserID
        {
            get { return HttpContext.Session["UserID"] == null ? 0 : Convert.ToInt32(HttpContext.Session["UserID"]); }
        }
        //登录用户名称    
        public string UserName
        {
            get { return HttpContext.Session["UserName"] == null ? "" : HttpContext.Session["UserName"].ToString(); }
        }
        //登录用户角色ID
        public string Role
        {
            get { return HttpContext.Session["Role"] == null ? "" : HttpContext.Session["Role"].ToString(); }
        }
        //登录用户角色名称   
        public string RoleName
        {
            get { return HttpContext.Session["RoleName"] == null ? "" : HttpContext.Session["RoleName"].ToString(); }
        }
        /// <summary>
        /// 页面加载前进行验证
        /// </summary>
        /// <param name="filterContext"></param>
        [NonAction]
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var bll = new UserBLL();
            var info = bll.GetPageByUrl(Request.Url);
            ViewBag.PageInfo = info;
            if (UserID == 0 && Session.Keys.Count == 0)//登录验证
            {
                Response.Redirect(Url.Action("Login", "Home"), true);
                return;
            }
            if (Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) ||
                info.Roles.Contains(string.Format(",{0},", Role))) return;
            Response.Redirect(Url.Action("Index", "Home"), true);
        }
        //控制器异常时
        [NonAction]
        protected override void OnException(ExceptionContext filterContext)
        {
            var result = new ViewResult { ViewName = "Error" };
            result.ViewBag.Msg = filterContext.Exception.Message;
            Infrastructure.Log.Error(Request.Url.ToString(), filterContext.Exception.Message);
            filterContext.Result = result;
            filterContext.ExceptionHandled = true;
        }
    }
}
